import cv2
import matplotlib.pyplot as plt

# 读取图像
image1 = cv2.imread('image1.jpg', cv2.IMREAD_GRAYSCALE)
image2 = cv2.imread('image2.jpg', cv2.IMREAD_GRAYSCALE)

# 创建ORB特征点检测器
orb = cv2.ORB_create()

# 检测特征点和计算描述符
kp1, des1 = orb.detectAndCompute(image1, None)
kp2, des2 = orb.detectAndCompute(image2, None)

# 创建BFMatcher对象
bf = cv2.BFMatcher(cv2.NORM_HAMMING)

# KNN匹配描述符
matches = bf.knnMatch(des1, des2, k=2)

# 过滤匹配结果
good_matches = []
for m, n in matches:
    if m.distance < 0.75 * n.distance:
        good_matches.append([m])

# 绘制匹配结果
image_matches = cv2.drawMatchesKnn(image1, kp1, image2, kp2, good_matches, None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

# 显示结果
plt.imshow(image_matches)
plt.title('KNN Matching')
plt.show()